package com.chen.config;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;

/**
 * 前后端分离的情况下, 登录成功返回json处理,
 * 写完这个类后, 要加载到基础的配置中WebSecurityConfig ,   form.successHandler(new MyAuthenticationSuccessHandler());
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        Object principal = authentication.getPrincipal(); //用户认证信息
        HashMap<Object, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message","success");
        result.put("data",principal);
        response.getWriter().print(JSON.toJSONString(result));
    }
}
